const Koa = require('koa')
const app = new Koa()
const config = require('./config')
const bodyparser = require('koa-bodyparser')
const cors = require('koa-cors')
const static = require('koa-static')
const path = require('path')
const router = require('./routes/index')

// 错误处理中间件
app.use(async (ctx,next) => {
    try{
        await next()
    }catch (e){
        console.log(`server err: ${e}`)
        ctx.status = 500;
        ctx.body = {
            code: 500,
            msg: 'server error!'
        }
    }
})

// 解析post请求请求体
app.use(bodyparser())

// 后端跨域
app.use(cors())

// 设置静态资源
app.use(static(path.join(__dirname, 'public')))

// 启用路由
app.use(router.routes(),router.allowedMethods())

app.listen(config.port,() => {
    console.log(`server is running on ${config.baseURL}:${config.port}`);
})